package com.ctcemti.mdm.project.tool.generatecode.controller;

import com.ctcemti.mdm.common.exception.UnCanConnectException;
import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.util.JdbcUtil;
import com.ctcemti.mdm.project.sys.entity.InfDisciplines;
import com.ctcemti.mdm.project.sys.entity.formdata.BaseReq;
import com.ctcemti.mdm.project.tool.generatecode.entity.GenTable;
import com.ctcemti.mdm.project.tool.generatecode.entity.GenTableColumn;
import com.ctcemti.mdm.project.tool.generatecode.entity.JDBCProperies;
import com.ctcemti.mdm.project.tool.generatecode.service.IGenTableColumnService;
import com.ctcemti.mdm.project.tool.generatecode.service.IGenTableService;
import com.ctcemti.mdm.project.tool.generatecode.util.Convert;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 代码生成 操作处理
 *
 * @author bxf
 */
@Controller
@RequestMapping("/tool/gen")
public class GenController extends BaseReq
{

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

//    @RequiresPermissions("tool:gen:view")
//    @GetMapping()
//    public String gen()
//    {
//        return prefix + "/gen";
//    }

    /**
     * 查询代码生成列表
     */
    //@RequiresPermissions("tool:gen:list")
    @PostMapping("/list")
    @ResponseBody
    public Result<PageInfo> genList(HttpServletRequest request,GenTable genTable)
    {
        PageHelper.startPage(genTable.getPageIndex(),genTable.getPageSize());
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        PageInfo<GenTable> pageInfo = new PageInfo(list);
        return new Result<PageInfo>(ResultEnum.SUCCESS,pageInfo);
    }

    /**
     * 查询代码生成列表
     */
    //@RequiresPermissions("tool:gen:list")
    @PostMapping("/jdbclist")
    @ResponseBody
    public Result<PageInfo> genJdbcList(HttpServletRequest request,GenTable genTable)
    {
        PageHelper.startPage(genTable.getPageIndex(),genTable.getPageSize());
        List<GenTable> list = genTableService.selectGenTableListForJDBC(genTable);
        PageInfo<GenTable> pageInfo = new PageInfo(list);
        return new Result<PageInfo>(ResultEnum.SUCCESS,pageInfo);
    }

    /**
     * 查询数据库列表
     */
    //@RequiresPermissions("tool:gen:list")
    @PostMapping("/db/list")
    @ResponseBody
    public Result<PageInfo> dataList(HttpServletRequest request, GenTable genTable)
    {
        //PageHelper.startPage(genTable.getPageIndex(),genTable.getPageSize());
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        PageInfo<GenTable> pageInfo = new PageInfo();
        pageInfo.setList(list);
        pageInfo.setTotal(list.size());
        return new Result<PageInfo>(ResultEnum.SUCCESS,pageInfo);
    }

    /**
     * 查询数据库列表
     */
    //@RequiresPermissions("tool:gen:list")
    @PostMapping("/db/listforJDBC")
    @ResponseBody
    public Result<PageInfo> dataListForJDBC(HttpServletRequest request, GenTable genTable, JDBCProperies jdbcProperies) throws SQLException, UnCanConnectException {
        //PageHelper.startPage(genTable.getPageIndex(),genTable.getPageSize());
        List<GenTable> list = genTableService.selectDbTableListByJDBC(genTable,jdbcProperies);
        PageInfo<GenTable> pageInfo = new PageInfo();
        pageInfo.setList(list);
        pageInfo.setTotal(list.size());
        return new Result<PageInfo>(ResultEnum.SUCCESS,pageInfo);
    }

    /**
     * 查询数据表字段列表
     */
    //@RequiresPermissions("tool:gen:list")
    @PostMapping("/column/list")
    @ResponseBody
    public Result<PageInfo> columnList(HttpServletRequest request,GenTableColumn genTableColumn)
    {
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn);
        PageInfo<GenTableColumn> pageInfo = new PageInfo();
        pageInfo.setList(list);
        pageInfo.setTotal(list.size());
        return new Result<PageInfo>(ResultEnum.SUCCESS,pageInfo);
    }

//    /**
//     * 导入表结构
//     */
//    @RequiresPermissions("tool:gen:list")
//    @GetMapping("/importTable")
//    public String importTable()
//    {
//        return prefix + "/importTable";
//    }

    /**
     * 导入表结构（保存）
     */
    //@RequiresPermissions("tool:gen:list")
    //@Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    @ResponseBody
    public Result importTableSave(String tables, HttpServletRequest request)
    {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return new Result<InfDisciplines>(ResultEnum.SUCCESS,null);
    }

    /**
     * 导入表结构（保存）
     */
    //@RequiresPermissions("tool:gen:list")
    //@Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PostMapping("/importTableSaveForJDBC")
    @ResponseBody
    public Result importTableSaveForJDBC(String tables, JDBCProperies jdbcProperies, HttpServletRequest request) throws UnCanConnectException {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNamesForJDBC(tableNames,jdbcProperies);
        genTableService.importGenTableForJDBC(tableList,jdbcProperies);
        return new Result<InfDisciplines>(ResultEnum.SUCCESS,null);
    }

    /**
     * 修改代码生成业务
     */
    @PostMapping("/editTableBytableId")
    @ResponseBody
    public Result edit(Long tableId, HttpServletRequest request)
    {
        GenTable table = genTableService.selectGenTableById(tableId);
        return new Result<InfDisciplines>(ResultEnum.SUCCESS,table);
    }

    /**
     * 修改保存代码生成业务
     */
    //@RequiresPermissions("tool:gen:edit")
    //@Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PostMapping(value="/edit")
    @ResponseBody
    public Result editSave(HttpServletRequest request,@RequestBody  GenTable genTable)
    {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return new Result<InfDisciplines>(ResultEnum.SUCCESS,null);
    }

    //@RequiresPermissions("tool:gen:remove")
    //@Log(title = "代码生成", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public Result remove(HttpServletRequest request,String ids)
    {
        genTableService.deleteGenTableByIds(ids);
        return new Result<InfDisciplines>(ResultEnum.SUCCESS,null);
    }

    @PostMapping("/testConnect")
    @ResponseBody
    public Result testConnect(HttpServletRequest request,JDBCProperies jdbcProperies) throws SQLException {
        if(jdbcProperies.getDatasourceType()==1){//mysql
            jdbcProperies.setDriver("com.mysql.cj.jdbc.Driver");
        }else if(jdbcProperies.getDatasourceType()==2){//oracle
            jdbcProperies.setDriver("oracle.jdbc.driver.OracleDriver");
        }else{//sqlserver
            jdbcProperies.setDriver("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        }
        Connection connect = JdbcUtil.getConnect(jdbcProperies);
        return new Result<InfDisciplines>(connect==null?ResultEnum.ZTSJ_1103:ResultEnum.SUCCESS,null);
    }
//
//    /**
//     * 预览代码
//     */
//    @RequiresPermissions("tool:gen:preview")
//    @GetMapping("/preview/{tableId}")
//    @ResponseBody
//    public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException
//    {
//        Map<String, String> dataMap = genTableService.previewCode(tableId);
//        return AjaxResult.success(dataMap);
//    }

    /**
     * 生成代码
     */
    @GetMapping("/common/download/genCode/{tableId}")
    public void genCode(HttpServletResponse response, @PathVariable("tableId") String tableId) throws IOException
    {
        byte[] data = genTableService.generatorCode(tableId);
        genCode(response, data);
    }

//    /**
//     * 批量生成代码
//     */
//    @RequiresPermissions("tool:gen:code")
//    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
//    @GetMapping("/batchGenCode")
//    @ResponseBody
//    public void batchGenCode(HttpServletResponse response, String tables) throws IOException
//    {
//        String[] tableNames = Convert.toStrArray(tables);
//        byte[] data = genTableService.generatorCode(tableNames);
//        genCode(response, data);
//    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}